<script setup lang="tsx">
import BaseInfo from './components/Detail/BaseInfo/index.vue'
import InvoicingInfo from './components/Detail/InvoicingInfo/index.vue'
import FileCabinet from './components/Detail/FileCabinet/index.vue'
import ApprovalRecord from './components/Detail/ApprovalRecord/index.vue'
import { getEnumApi } from '@/api/invoice'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { ref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useRouter, useRoute } from 'vue-router'
import { getDetApi, cancelInvoiceApi } from '@/api/invoice'
import { CurdData, FieldEnum } from '@/api/invoice/types'
import { SelectOption } from '@/api/global/types'
import { createImageViewer } from '@/components/ImageViewer'
import { useEnumeratePicker } from '@/utils'
import { uploadInvoiceApi, checkInvoiceApi } from '@/api/invoice'
import { getSelectListApi as getOperatorSelectListApi } from '@/api/operator'
import { ElMessageBox } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()
const { push, go } = useRouter()

const { query } = useRoute()
const route = useRoute()
const { t } = useI18n()

const isLoading = ref(true) // 设置加载状态
const currentRow = ref<Nullable<CurdData>>(null)
const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])

let operatorOptions: SelectOption[] = []
let customerOption: SelectOption[] = []
let orderOption: SelectOption[] = []
let statusOption: SelectOption[] = [] // 明确指定类型 Option[]

const state = reactive({
  source: decodeURIComponent(route.query.source as string) || '',
  invoiceAttachList: ref<any[]>([]) // 附件列表
})

const getCustomeDet = async () => {
  try {
    tableLoading.value = true
    const res = (await getDetApi(query.id as string)) as any
    currentRow.value = res.data
    customerOption = currentRow?.value?.customer_option
    orderOption = currentRow?.value?.order_option

    dataList.value = res.data.items || []
    tableLoading.value = false
  } catch (e) {
    tableLoading.value = false
  }
}

const fetchData = async () => {
  await getCustomeDet()

  await getEnumApi({ field: 'all' }).then((res) => {
    statusOption = res.data.status
  })

  await getOperatorSelectListApi({}).then((res) => {
    operatorOptions = res.data.list
  })
  isLoading.value = false // 数据加载完成后更新状态
}

const handleClick = (tab: any, event: Event) => {
  console.log(tab, event)
}

// 跳转编辑
const action = (row, type: string) => {
  push(
    `/order/invoice-management/${type}?id=${row.id}&source=/order/invoice-management/detail?id=${row.id}`
  )
}
// 审核打开一个弹框，可以驳回和确认
const examineInvoice = (row, type) => {
  let params = {
    id: row.id,
    status: type
  }
  if (type == 2) {
    ElMessageBox.confirm('确定要驳回吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      // 确认操作
      console.log('用户点击了确定')
      checkInvoiceApi(params).then((res) => {
        console.log('res', res)
        if (res.code == 0) {
          ElMessage.success('审核驳回')
          getCustomeDet()
        }
      })
    })
  } else {
    ElMessageBox.confirm('确定要通过吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      // 确认操作
      console.log('用户点击了确定')
      checkInvoiceApi(params).then((res) => {
        console.log('res', res)
        if (res.code == 0) {
          ElMessage.success('审核通过')
          getCustomeDet()
        }
      })
    })
  }
}

//返回
const back = () => {
  const backurl = state.source !== 'undefined' ? state.source : '/order/invoice-management'
  push(backurl)
}

const activeName = ref('base_info')
// 根据 activeName 动态选择渲染的组件
const currentTabComponent = computed(() => {
  switch (activeName.value) {
    case 'base_info':
      return BaseInfo // 需要先定义 BaseInfo 组件
    case 'invoicing_info':
      return InvoicingInfo // 需要先定义 InvoicingInfo 组件
    case 'file_cabinet':
      return FileCabinet // 需要先定义 FileCabinet 组件
    case 'approval_record':
      return ApprovalRecord // 需要先定义 ApprovalRecord 组件
    default:
      return 'base_info' // 默认渲染 BaseInfo 组件
  }
})
// 定义选项
const options = [{ label: '新建发票', value: 'newInvoice' }]

// 搜索文本
const searchText = ref('')

// 过滤后的选项
const filteredOptions = ref([...options])

// 过滤方法
const filterOptions = () => {
  filteredOptions.value = options.filter((item) => item.label.includes(searchText.value))
}

// 处理下拉菜单的操作
const handleCommand = (command) => {
  console.log('执行的操作：', command)
  switch (command) {
    case 'newContract':
      push('/contract/contractList/add')
      break
    case 'newInvoice':
      push(
        '/order/invoice-management/add?customer_id=' +
          currentRow?.value?.id +
          '&cusname=' +
          currentRow?.value?.invoice_no
      )
      break
    case 'newOpportunity':
      push('/opportunity/opportunityList/add')
      break
    case 'newUnpaidInvoice':
      push('/invoice/invoiceList/add')
      break
    case 'setFollowReminder':
      push('/customer/customerList/add')
      break
    case 'newFollowLog':
      push('/customer/customerList/add')
  }
}

const dialogVisible = ref(false)
const fileList = ref([])

const closeDialog = () => {
  dialogVisible.value = false
}

//上传成功以后回调
const handleUploadCallback = (val: any) => {
  state.invoiceAttachList.push(val)
}
const handleRemoveFile = (val: any) => {
  if (state.invoiceAttachList && state.invoiceAttachList.length) {
    state.invoiceAttachList = state.invoiceAttachList.filter((item: Record<string, any>) => {
      item.uploadFile.uid !== val.uid
    })
  }
}

const handlePictureCardPreview = (val: any) => {
  if (!val) return
  createImageViewer({
    urlList: [val],
    zIndex: 99999
  })
}

const submitForm = () => {
  if (!state.invoiceAttachList.length) {
    ElMessage.error('请上传发票')
    return
  }
  const confirmationMessage =
    '您确认上传发票吗？上传后，发票将进入完成状态，无法进行修改或再次上传。请谨慎操作，确保信息准确。'

  ElMessageBox.confirm(confirmationMessage, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const loading = ref(false)
    loading.value = true
    const res = await uploadInvoiceApi({
      id: currentRow?.value?.id,
      invoice_attach: state.invoiceAttachList.map((item) => item.id).join(',')
    })
      .catch(() => {})
      .finally(() => {
        loading.value = false
        go(0)
      })
    if (res) {
      // 关闭弹窗
      closeDialog()
    }
  })
  // .catch(() => {
  //   data.row.status = originalStatus
  // })
  // 处理表单提交的逻辑
  console.log('提交上传的文件列表:', fileList.value)
}
// 上传发票
const uploadInvoice = () => {
  dialogVisible.value = true
}
fetchData()

//撤销编辑
const handleCancel = (row: any) => {
  ElMessageBox.confirm(t('common.message.operate'), t('common.tip'), {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let params = {
        id: row.id
      }
      let res = await cancelInvoiceApi(row.id, params)
      console.log('res', res)
      if (res.code === 0) {
        ElMessage.success('撤销成功')
        getCustomeDet()
      }
    })
    .catch(() => {})
}
</script>

<template>
  <ContentDetailWrap :title="t('customer.detail')" @back="push('/customer/customerList')">
    <template #header v-if="!isLoading">
      <div class="header flex justify-between items-center">
        <div class="header-left flex flex-start items-center">
          <div class="right"
            ><div class="top">
              <p :style="{ fontWeight: 'bold', color: 'black' }"> {{ currentRow?.invoice_no }} </p>
            </div>
            <div class="bottom">
              <el-tag type="success" size="small" v-if="currentRow?.status">
                {{ useEnumeratePicker(statusOption, currentRow?.status) }}
              </el-tag>
            </div>
          </div>
        </div>
        <div class="header-right">
          <!-- 操作按钮 -->

          <BaseButton type="success" @click="uploadInvoice()" v-if="currentRow?.status == 10">
            上传发票
          </BaseButton>

          <BaseButton
            type="primary"
            @click="handleCancel(currentRow)"
            v-if="currentRow?.status == 1 && userStore.getUserInfo?.id == currentRow.creator"
          >
            {{ t('common.cancelExamine') }}
          </BaseButton>
          <BaseButton
            type="primary"
            @click="action(currentRow, 'edit')"
            v-if="currentRow?.status == 1"
          >
            {{ t('action.edit') }}
          </BaseButton>
          <BaseButton @click="examineInvoice(currentRow, 2)" v-if="currentRow?.status == 1">
            {{ t('purchase.examine') }}{{ t('common.reject') }}
          </BaseButton>
          <BaseButton
            type="primary"
            @click="examineInvoice(currentRow, 1)"
            v-if="currentRow?.status == 1"
          >
            {{ t('purchase.examine_pass') }}
          </BaseButton>

          <BaseButton @click="back">
            {{ t('action.back') }}
          </BaseButton>
        </div>
      </div>
      <el-divider />
      <div class="nav flex flex-start items-center">
        <div class="div">
          <text>{{ t('invoice.invoice_no') }}: {{ currentRow?.invoice_no ?? '' }}</text>
        </div>
        <div class="div">
          <text
            >{{ t('invoice.customer_id') }}:
            {{ useEnumeratePicker(customerOption, currentRow?.customer_id ?? '') }}</text
          >
        </div>
        <div class="div">
          <text
            >{{ t('invoice.order_id') }}:
            {{ useEnumeratePicker(orderOption, currentRow?.order_id ?? '') }}</text
          >
        </div>
        <div class="div">
          <text>{{ t('invoice.invoicing_date') }}: {{ currentRow?.invoicing_date ?? '' }}</text>
        </div>
        <div class="div">
          <text>{{ t('invoice.invoice_amount') }}: {{ currentRow?.invoice_amount ?? '' }}</text>
        </div>
      </div>
      <br />
      <div>
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane label="基本信息" name="base_info" />
          <el-tab-pane label="开票信息" name="invoicing_info" />
          <el-tab-pane label="文件柜" name="file_cabinet" />
          <el-tab-pane label="审批记录" name="approval_record" />
        </el-tabs>
        <!-- 动态加载对应的 tab 内容 -->
        <component
          :is="currentTabComponent"
          :current-row="currentRow"
          :operator-options="operatorOptions"
        />
      </div>
    </template>
    <!-- 上传文件弹窗 -->
    <el-dialog title="上传发票" v-model="dialogVisible" width="50%" @close="closeDialog">
      <UploadFile
        class="w-100%"
        url="/common/uploadFile"
        drag
        :file-type="['png', 'jpg', 'jpeg', 'bmp', 'pdf', 'docx', 'doc', 'xlsx', 'xls']"
        :params="{ directory: 11 }"
        :limit="9"
        upload-file-button-name="点击上传或拖拽到此处上传"
        buttonWidth="100%"
        :button-link="true"
        :show-file-list="true"
        @upload-success-res="handleUploadCallback"
        @handle-remove-file="handleRemoveFile"
        @handle-picture-card-preview="handlePictureCardPreview"
      />

      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </ContentDetailWrap>
</template>

<style lang="less" scoped>
:deep(.el-upload-list__item .el-icon--close:hover) {
  color: transparent !important;
  opacity: 0 !important;
  visibility: hidden;
}

:deep(.el-upload-list__item:hover .el-icon--close) {
  display: none;
}

:deep(.el-upload-list__item.is-success:focus:not(:hover)) {
  display: none !important;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 10px; /* 增加间距，使按钮不会挤在一起 */
}

.header-left .left {
  flex-direction: column;
  justify-content: space-around;
  margin-right: 10px;
}

.header-left .right .bottom span {
  margin-right: 10px;
}

.nav {
  gap: 50px;
}

.button-group {
  display: flex;
  align-items: center;
  gap: 0; /* 确保按钮组不额外增加间距 */
}

/* 主按钮样式 */
.main-button {
  margin-right: -1px; /* 让按钮无间隙连接 */
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

/* 下拉三角按钮 */
.triangle-button {
  display: flex;
  padding: 0 12px;
  border-bottom-left-radius: 0;
  border-top-left-radius: 0;
  align-items: center;
  justify-content: center;
}
</style>
